package com.durian.base.net;

import androidx.collection.ArrayMap;

import android.text.TextUtils;

import com.durian.base.net.cache.IHttpCacheManager;
import com.durian.base.net.cache.NoneHttpCacheManager;
import com.durian.base.net.listener.OnCreateOkHttpBuilderListener;
import com.durian.base.net.monitor.HttpMonitor;
import com.durian.base.net.monitor.HttpMonitorListener;
import com.durian.base.net.request.DefultRequestFactroy;
import com.durian.base.rxhttp.RxHttp;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;

import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okio.Buffer;

/**
 * 说明：HttpConfig
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019/1/31 09:45
 * <p/>
 * 版本：version 1.0
 */
public class HttpConfig {

    public interface Constant {
        /**
         * 默认超时时间10s
         */
        long   TIME_OUT = 10;
        /**
         * 打印日志
         */
        String TAG      = "OkHttpResult";
    }

    public interface ErrorCode {
        /**
         * 请求超时
         */
        int TIME_OUT         = -99999;
        /**
         * 响应为空
         */
        int RESPONSE_IS_NULL = -99998;
        /**
         * 未知错误
         */
        int UNKNOW           = -99997;
    }

    private static HttpConfig sConfig = new HttpConfig();

    /**
     * 设置超时时间，单位秒，默认10秒
     */
    private long                          mTimeout = Constant.TIME_OUT;
    /**
     * 调试模式
     */
    private boolean                       isDebug  = false;
    /**
     * 全局Headers
     */
    private ArrayMap<String, String>      mHaders;
    /**
     * 全局参数
     */
    private List<Part>                    mCommonParams;
    //证书列表
    private List<InputStream>             mCertificateList;
    private GlobalHttpBlocker             mGlobalHttpBlocker;
    private HostnameVerifier              mHostnameVerifier;
//    private OkHttpClient                  mOkHttpClient;
//    private OkHttpClient.Builder          mOkHttpClientBuilder;
    private DefultRequestFactroy          mDefultRequestFactroy;
    private IHttpCacheManager             mCacheManager;
    private OnCreateOkHttpBuilderListener mOnCreateOkHttpBuilderListener;

    private HttpConfig() {
        mCacheManager = NoneHttpCacheManager.create();
    }

    public static HttpConfig get() {
        return sConfig;
    }

    /**
     * 设置拦截器
     * @param globalHttpBlocker
     */
    public void setGlobalHttpBlocker(GlobalHttpBlocker globalHttpBlocker) {
        mGlobalHttpBlocker = globalHttpBlocker;
    }

    public GlobalHttpBlocker getGlobalHttpBlocker() {
        return mGlobalHttpBlocker;
    }

    /**
     * 设置缓存管理器
     *
     * @param manager
     * @return
     */
    public HttpConfig setHttpCacheManager(IHttpCacheManager manager) {
        if (manager != null) {
            this.mCacheManager = manager;
        }
        return this;
    }

    public IHttpCacheManager getCacheManager() {
        return mCacheManager;
    }

    public void setOnCreateOkHttpBuilderListener(OnCreateOkHttpBuilderListener onCreateOkHttpBuilderListener) {
        mOnCreateOkHttpBuilderListener = onCreateOkHttpBuilderListener;
    }

    /**
     * 移除HTTP监听器
     *
     * @param listener
     * @return
     */
    public HttpConfig removeMonitor(HttpMonitorListener listener) {
        HttpMonitor.get().removeListener(listener);
        return this;
    }

    /**
     * 添加HTTP监听器
     *
     * @param listener
     * @return
     */
    public HttpConfig addMonitor(HttpMonitorListener listener) {
        HttpMonitor.get().addListener(listener);
        return this;
    }

    /**
     * 设置全局参数
     *
     * @param params
     * @return
     */
    public HttpConfig setCommonParams(List<Part> params) {
        this.mCommonParams = params;
        return this;
    }

    /**
     * 添加全局参数
     *
     * @param param
     * @return
     */
    public HttpConfig addCommonParam(Part param) {
        if (param != null) {
            if (mCommonParams == null) {
                mCommonParams = new ArrayList<>();
            }
            mCommonParams.add(param);
        }
        return this;
    }

    /**
     * 设置全局Headers
     *
     * @param headers
     * @return
     */
    public HttpConfig setCommonHeaders(Headers headers) {
        if (mHaders == null) {
            mHaders = new ArrayMap<>();
        } else {
            mHaders.clear();
        }
        if (headers != null) {
            for (String key : headers.names()) {
                mHaders.put(key, headers.get(key));
            }
        }
        return this;
    }

    /**
     * 添加全局Header
     *
     * @param key
     * @param value
     * @return
     */
    public HttpConfig addCommonHeader(String key, String value) {
        if (mHaders == null) {
            mHaders = new ArrayMap<>();
        }
        if (!TextUtils.isEmpty(key)) {
            mHaders.put(key, value == null ? "" : value);
        }
        return this;
    }

    public DefultRequestFactroy getDefultRequestFactroy() {
        return mDefultRequestFactroy;
    }

    public HttpConfig setDefaultRequestFactroy(DefultRequestFactroy factroy) {
        this.mDefultRequestFactroy = factroy;
        return this;
    }

    /**
     * 添加全局Header
     *
     * @param key
     * @return
     */
    public HttpConfig addCommonHeader(String key) {
        addCommonHeader(key, "");
        return this;
    }

    /**
     * 设置超时时间
     *
     * @param time
     * @return
     */
    public HttpConfig setCommonTimeOut(long time) {
        this.mTimeout = time;
        return this;
    }

    /**
     * 开启调试
     *
     * @param isDebug
     * @return
     */
    public HttpConfig setDebug(boolean isDebug) {
        this.isDebug = isDebug;
        return this;
    }

    /**
     * 说明：添加证书
     *
     * @param certificates
     * @return
     */
    public HttpConfig setCertificates(InputStream... certificates) {
        if (mCertificateList == null) {
            mCertificateList = new ArrayList<>();
        }
        for (InputStream is : certificates) {
            if (is != null) {
                mCertificateList.add(is);
            }
        }
        return this;
    }

    /**
     * 说明：添加证书
     *
     * @param certificates
     * @return
     */
    public HttpConfig setCertificates(String... certificates) {
        if (mCertificateList == null) {
            mCertificateList = new ArrayList<>();
        }
        for (String s : certificates) {
            if (!TextUtils.isEmpty(s)) {
                mCertificateList.add(new Buffer().writeUtf8(s).inputStream());
            }
        }
        return this;
    }

    public HttpConfig setHostnameVerifier(HostnameVerifier hostnameVerifier) {
        this.mHostnameVerifier = hostnameVerifier;
        return this;
    }

//    public synchronized OkHttpClient.Builder clientBuilder() {
//        if (mOkHttpClientBuilder == null) {
//            mOkHttpClientBuilder = new OkHttpClient.Builder();
//            /**
//             * 设置超时时间
//             */
//            mOkHttpClientBuilder.connectTimeout(mTimeout, TimeUnit.SECONDS);
//            mOkHttpClientBuilder.writeTimeout(mTimeout, TimeUnit.SECONDS);
//            mOkHttpClientBuilder.readTimeout(mTimeout, TimeUnit.SECONDS);
//            /**
//             * 设置证书
//             */
//            if (mCertificateList != null && !mCertificateList.isEmpty()) {
//                HttpsCerManager httpsCerManager = new HttpsCerManager(mOkHttpClientBuilder);
//                httpsCerManager.setCertificates(mCertificateList);
//            } else {
//                HttpsCerManager httpsCerManager = new HttpsCerManager(mOkHttpClientBuilder);
//                httpsCerManager.setTrustAll();
//            }
//            if (mHostnameVerifier != null) {
//                mOkHttpClientBuilder.hostnameVerifier(mHostnameVerifier);
//            }
//            if (mOnCreateOkHttpBuilderListener != null) {
//                mOnCreateOkHttpBuilderListener.createHttpBuilder(mOkHttpClientBuilder);
//            }
//        }
//        return mOkHttpClientBuilder;
//    }

    public List<Part> getCommonParams() {
        return mCommonParams;
    }

    public Headers getCommonHeaders() {
        Headers.Builder builder = null;
        if (mHaders != null && !mHaders.isEmpty()) {
            builder = new Headers.Builder();
            for (Map.Entry<String, String> entry : mHaders.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        if (builder == null) {
            return null;
        } else {
            return builder.build();
        }
    }

    public boolean isDebug() {
        return isDebug;
    }

    public OkHttpClient client() {
//        if (mOkHttpClient == null) {
//            mOkHttpClient = RxHttp.getOkHttpClient();
//        }
        return RxHttp.getOkHttpClient();
    }
}
